// pages/track/track.js
const { searchLogistic } = require('../../services/logistic')

Page({
  data:{
    carrier:'',
    waybillNumber:'',
    statusText:'',
    sender:'',
    receiver:'',
    events:[],
    loading:false,
    info: {
      send_name: '',
      send_mobile: '',
      receive_mobile: ''
    },
    userInfo: null
  },
  onLoad(options){
    const waybill = options.waybill || ''
    const carrier = options.carrier || '未知承运商'
    const searchType = options.search_type ? parseInt(options.search_type) : 0
    const checkPhone = options.check_phone || ''
    this.setData({
      carrier: carrier,
      waybillNumber: waybill,
      searchType: searchType,
      checkPhone: checkPhone
    })
    if (waybill) {
      this.fetchTrack(waybill)
    }
  },
  onShow(){
    try{
      const user = wx.getStorageSync('user') || null
      this.setData({ userInfo: user })
    }catch(e){
      this.setData({ userInfo: null })
    }
  },
  async fetchTrack(waybill){
    this.setData({ loading: true })
    wx.showLoading({ title: '查询中...' })
    try{
      const params = { scan_text: waybill }
      if (this.data.searchType) params.search_type = this.data.searchType
      if (this.data.checkPhone) params.check_phone = this.data.checkPhone
      const res = await searchLogistic(params)
      const logistics = Array.isArray(res.data.logistics) ? res.data.logistics : []
      const events = Array.isArray(res.data.routing_log) ? res.data.routing_log : []
      if(res.code === 1) {
        let arr = logistics.reverse()
        this.setData({
          statusText: res.data.routing_log[0]?.type || '',
          sender: res.data.send_name || '',
          receiver: res.data.receive_name || '',
          events: arr.concat(events),
          info: res.data
        })
      } else {
        wx.showToast({ title: res.msg || '查询失败', icon:'none', duration: 3000 })
        this.setData({
          events: [{remark: '暂无数据', acceptDate: '', acceptTime: ''}]
        })
      }
    }catch(err){
      console.error('查询失败', err)
      wx.showToast({ title:'查询失败', icon:'none', duration: 3000 })
    }finally{
      this.setData({ loading:false })
      wx.hideLoading()
    }
  }
  
})

